<template>
  <div class="login-page">
    <div class="login-container">
      <h2 class="login-title">用户登录</h2>
      <el-form
          :model="loginForm"
          :rules="rules"
          ref="loginFormRef"
          @submit.prevent="handleSubmit"
          class="login-form"
      >
        <el-form-item prop="username">
          <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              clearable
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              v-model="loginForm.password"
              placeholder="请输入密码"
              type="password"
              show-password
              clearable
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              native-type="submit"
              :loading="isLoading"
              class="login-button"
          >
            {{ isLoading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>

        <el-form-item>
          <el-button
              type="success"
              @click="startFaceRecognition"
              :loading="isFaceRecognitionLoading"
              class="face-recognition-button"
          >
            {{ isFaceRecognitionLoading ? '识别中...' : '人脸识别登录' }}
          </el-button>
        </el-form-item>
      </el-form>

      <div class="login-link">
        还没有账号？<router-link to="/reg">立即注册</router-link>
      </div>

      <!-- 人脸识别视频区域 -->
      <video
          ref="videoRef"
          autoplay
          playsinline
          class="face-video"
          v-show="isFaceRecognitionLoading"
      ></video>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeUnmount } from 'vue'
import axios from 'axios'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from "element-plus"
import * as faceapi from 'face-api.js'

const loginForm = ref({
  username: '',
  password: '',
  faceToken: ''
})

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const isLoading = ref(false)
const isFaceRecognitionLoading = ref(false)
const loginFormRef = ref(null)
const videoRef = ref(null)
let stream = null

const startFaceRecognition = async () => {
  try {
    isFaceRecognitionLoading.value = true
    stream = await navigator.mediaDevices.getUserMedia({ video: true })
    videoRef.value.srcObject = stream

    // 加载人脸识别模型
    await faceapi.nets.tinyFaceDetector.loadFromUri('/models')
    await faceapi.nets.faceRecognitionNet.loadFromUri('/models')
    await faceapi.nets.faceLandmark68Net.loadFromUri('/models')

    const detectFace = async () => {
      const detection = await faceapi.detectSingleFace(
          videoRef.value,
          new faceapi.TinyFaceDetectorOptions()
      )

      if (detection) {
        loginForm.value.faceToken = 'generated_face_token'
        isFaceRecognitionLoading.value = false
        stopFaceRecognition()
        handleSubmit()
      } else {
        requestAnimationFrame(detectFace)
      }
    }

    detectFace()
  } catch (error) {
    console.error('人脸识别错误:', error)
    ElMessage.error("无法访问摄像头或检测人脸")
    isFaceRecognitionLoading.value = false
    if (stream) {
      stream.getTracks().forEach(track => track.stop())
    }
  }
}

const stopFaceRecognition = () => {
  if (stream) {
    stream.getTracks().forEach(track => track.stop())
  }
  if (videoRef.value) {
    videoRef.value.srcObject = null
  }
}

const handleSubmit = async () => {
  try {
    await loginFormRef.value.validate()
    isLoading.value = true

    axios.post(BASE_URL + '/api/v1/users/login', loginForm.value)
        .then(response => {
          if (response.data.code === 2000) {
            ElMessage.success("登录成功")
            const data = response.data.data
            const userData = data.user
            const token = data.token

            const storeUser = {
              id: userData.id || userData.userId,   // 兼容两种后端命名
              username: userData.username,
              phone: userData.phone,
              realName: userData.realName,
              avatarUrl: userData.avatarUrl
            };

            // 兼容性处理
            if (!userData.userId && userData.id) {
              userData.userId = userData.id
            }

            localStorage.setItem('user', JSON.stringify(userData))
            localStorage.setItem('token', token)
            localStorage.setItem('user', JSON.stringify(storeUser));

            window.location.href = '/familyuser'
          } else {
            ElMessage.error(response.data.message)
          }
        })
        .catch(error => {
          console.error('请求失败:', error)
          ElMessage.error("请求失败，请稍后再试")
        })
        .finally(() => {
          isLoading.value = false
        })
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error("表单验证失败，请检查输入")
    isLoading.value = false
  }
}

onBeforeUnmount(() => {
  stopFaceRecognition()
})
</script>

<style scoped>
.login-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f2f5;
}

.login-container {
  width: 300px;
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  background-color: #fff;
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-size: 24px;
}

.login-form {
  margin-top: 20px;
}

.login-button,
.face-recognition-button {
  width: 100%;
  margin-top: 10px;
}

.face-video {
  width: 100%;
  margin-top: 20px;
  border-radius: 8px;
}

.login-link {
  margin-top: 20px;
  text-align: center;
  color: #666;
}

.login-link a {
  color: #409eff;
  text-decoration: none;
}

.login-link a:hover {
  text-decoration: underline;
}
</style>